package mobi.weq.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import mobi.weq.db.Database;
import mobi.weq.model.HealthCondition;
import mobi.weq.model.User;

public class UserDao {
	public synchronized int addUser(User s) throws SQLException {
		Connection c = Database.getConnection();
		String query = "insert into users(user_id,username,email,city,country,gender,age_group,password) values(?,?,?,?,?,?,?,?)";
		PreparedStatement ps = c.prepareStatement(query);
		ps.setString(1, s.getUserId());
		ps.setString(2, s.getUserName());
		ps.setString(3, s.getEmail());
		ps.setString(4, s.getCity());
		ps.setString(5, s.getCountry());
		ps.setString(6, s.getGender());
		ps.setString(7, s.getAgeGroup());
		ps.setString(8, s.getPassword());

		HealthConditionDao sd = new HealthConditionDao();
		HealthCondition hc = new HealthCondition();
		hc.setUserId(s.getUserId());
		ps.executeUpdate();
		return sd.addHealthCondition(hc);

	}

	public List<User> getAllUsers() throws SQLException {
		Connection c = Database.getConnection();
		String query = "select * from users";
		PreparedStatement ps = c.prepareStatement(query);

		ResultSet rs = ps.executeQuery();
		List<User> users = new ArrayList<User>();

		while (rs.next()) {
			User us = getUserFromResultSet(rs);
			users.add(us);
		}
		return users;

	}

	public User getUserByUsernamePassword(String username, String password)
			throws SQLException {
		Connection c = Database.getConnection();
		String query = "select * from users where username=? and password=?";
		PreparedStatement ps = c.prepareStatement(query);
		ps.setString(1, username);
		ps.setString(2, password);

		ResultSet rs = ps.executeQuery();

		if (rs.next()) {
			User us = getUserFromResultSet(rs);
			return us;
		}
		return null;

	}

	private User getUserFromResultSet(ResultSet rs) throws SQLException {
		User us = new User();
		us.setUserId(rs.getString(1));
		us.setUserName(rs.getString(2));
		us.setEmail(rs.getString(3));
		us.setCity(rs.getString(4));
		us.setCountry(rs.getString(5));
		us.setGender(rs.getString(6));
		us.setAgeGroup(rs.getString(7));
		us.setPassword(rs.getString(8));
		return us;
	}

	public synchronized int deleteUser(User s) throws SQLException {

		Connection cn = Database.getConnection();
		String sql = "delete from user where (?)=(?)";
		PreparedStatement ps = cn.prepareStatement(sql);
		return ps.executeUpdate();

	}

	public static void main(String[] args) throws SQLException {
		User us = new User();
		us.setUserName("FLy");
		UserDao ud = new UserDao();

		System.out.println(ud.addUser(us));
	}

}
